﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;
using TJADRICD.CollaborativeDesignPlugin;
using TJADRICD.BLL;
using TJADRICD.Model;

using DNA;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;

namespace TJADRICD.CollaborativeDesignPlugin
{
    class CommandFrame
    {
        static public FrameInfo lastFrameInfo = new FrameInfo();

        //工具函数，用来将设计院提供的图框文件整理成新的属性块形式
        //把文件中的文字都转入指定块的相应位置成为属性
        [CommandMethod("Text2Attr")]
        public static void Text2Attr()
        {
            //选择作为容器的图块
            List<string> blockNames = new List<string>();
            string blockName;
            Tools.WriteMessageWithReturn("已有图块为：");
            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(Tools.Database.BlockTableId, OpenMode.ForWrite);
                foreach (ObjectId blockId in table)
                {
                    BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                    if (record.Name[0] == '*') continue;
                    blockNames.Add(record.Name);
                    Tools.WriteMessageWithReturn(String.Format("({0}) {1}", blockNames.Count.ToString(), record.Name));
                }
            }
            PromptIntegerResult res = Tools.Editor.GetInteger("请选择作为容器的图块的序号");
            if (res.Status != PromptStatus.OK)
            {
                return;
            }
            else
            {
                blockName = blockNames[res.Value - 1];
            }

            //获得所有的文字
            List<DBObject> objs = Tools.GetAllObjectsInModelSpace(Tools.Database);
            List<DBObject> texts = new List<DBObject>();
            foreach (DBObject obj in objs)
            {
                if (obj is DBText)
                {
                    texts.Add(obj);
                }
            }
            //把文字依次放入块中
            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(Tools.Database.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord record = (BlockTableRecord)trans.GetObject(table[blockName], OpenMode.ForWrite);

                foreach (DBText text in texts)
                {
                    try
                    {
                        AttributeDefinition attrDef = new AttributeDefinition(text.Position, text.TextString, text.TextString, text.TextString, new ObjectId());

                        attrDef.Position = text.Position;
                        attrDef.Height = text.Height;
                        attrDef.Rotation = text.Rotation;
                        attrDef.WidthFactor = text.WidthFactor;

                        record.AppendEntity(attrDef);
                        trans.AddNewlyCreatedDBObject(attrDef, true);
                    }
                    catch (System.Exception ex)
                    {
                        Tools.WriteMessageWithReturn(ex.StackTrace);
                        Tools.WriteMessageWithReturn(ex.Message);
                    }
                }

                trans.Commit();
            }

            Tools.WriteMessageWithReturn("已将" + texts.Count + "个文字转入" + blockName + "块中！");
        }
        public static ObjectId TK_Layer()
        {
            ObjectId layerId;
            Database db = HostApplicationServices.WorkingDatabase;
            Transaction trans = db.TransactionManager.StartTransaction();
            LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);
            if (lt.Has("TK"))
            {
                layerId = lt["TK"];
            }
            else
            {
                LayerTableRecord ltr = new LayerTableRecord();
                ltr.Name = "TK";
                ltr.Color = Autodesk.AutoCAD.Colors.Color.FromColor(Color.Black);
                layerId = lt.Add(ltr);
                trans.AddNewlyCreatedDBObject(ltr, true);
            }
            trans.Commit();
            return layerId;
        }
        /// <summary>
        /// 选择图框名
        /// </summary>
        public static string SelectFrame()
        {
            //选择图框
            string[] frameNames = Enum.GetNames(typeof(FrameType));
            string frameName;
            for (int i = 0; i < frameNames.Length; i++)
            {
                Tools.WriteMessageWithReturn(string.Format("({0}) {1}", i, frameNames[i]));
            }
            PromptIntegerResult res = Tools.Editor.GetInteger("请输入需要图框的序号");
            if (res.Status != PromptStatus.OK)
            {
                return "";
            }
            else
            {
                frameName = frameNames[res.Value];
                return frameName;
            }

        }



        public static void LoadActualFrame(string frameName)
        {
            DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            string framePath = Config.FramePath + frameName + ".dwg";
            Tools.WriteMessageWithReturn(frameName);
            //从图框文件中读出图框块
            ObjectIdCollection blockIds = new ObjectIdCollection();
            Database srcDB = new Database(false, true);
            try
            {
                srcDB.ReadDwgFile(framePath, System.IO.FileShare.Read, true, "");
            }
            catch (System.Exception ex)
            {
                Tools.WriteMessageWithReturn(ex.Message);
            }
            using (Transaction trans = srcDB.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(srcDB.BlockTableId, OpenMode.ForRead, false);
                foreach (ObjectId blockId in table)
                {
                    BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                    if (!record.IsAnonymous && !record.IsLayout && record.Name == frameName)
                    {
                        blockIds.Add(blockId);
                    }
                }
            }
            //将图框块复制到当前数据库中
            IdMapping mapping = new IdMapping();
            srcDB.WblockCloneObjects(blockIds, Tools.Database.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);

            Tools.WriteMessageWithReturn(string.Format("从{0}复制了{1}个块到当前数据库中", framePath, blockIds.Count));
            srcDB.Dispose();
//            ImportBlockToDB(frameName, Tools.Database);
        }

        // 从图框路径中读入图框文件，创建块定义（但没有Insert）
        [CommandMethod("LoadFrame")]
        public static void LoadFrame()
        {
            string frameName = SelectFrame();
            if (frameName == "")
                return;
            LoadActualFrame(frameName);
        }

        // 获取当前文件中某个图框信息
        public static FrameInfo GetSingleFrameInfo(Transaction trans, ObjectId frameId, ref string strCTB)
        {
            FrameInfo frameInfo = new FrameInfo();

            BlockTableRecord btr = (BlockTableRecord)trans.GetObject(Tools.Database.CurrentSpaceId, OpenMode.ForRead);
            foreach (ObjectId objId in btr)
            {
                if (objId == frameId)
                {
                    ObjectId blockRefId = frameId;
                    BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                    frameInfo.scale = 100;
                    frameInfo.frameType = "A0";

                    if (blockRef.ExtensionDictionary == ObjectId.Null)
                    {
                        frameInfo.strCTB = "null";
                    }
                    else
                    {
                        DBDictionary entXrecord = trans.GetObject(blockRef.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
                        ObjectId idDictionary = entXrecord.GetAt("MyXrecord");
                        Xrecord xRecord = trans.GetObject(idDictionary, OpenMode.ForRead) as Xrecord;
                        ResultBuffer rb = xRecord.Data;
                        foreach (TypedValue value in rb)
                        {
                            frameInfo.strCTB = value.Value.ToString();
                            Tools.WriteMessageWithReturn("3" + value.Value.ToString());
                        }
                    }

                    //frameInfo.Type = (FrameVersionType)Enum.Parse(typeof(FrameVersionType), blockRef.Name);
                    AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                    List<AttributeReference> attrRefs = new List<AttributeReference>();
                    foreach (ObjectId attrRefId in blockRefAttrs)
                    {
                        AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForRead);
                        attrRefs.Add(attrRef);
                    }
                    frameInfo.LoadFromAttrRefs(attrRefs);
                    break;
                }
            }
            return frameInfo;
        }


        /// <summary>
        /// 获取当前文件中所有的图框信息
        /// </summary>
        /// <returns>返回储存frameinfo的list</returns>
        public static List<FrameInfo> GetFrameInfo()
        {
            List<FrameInfo> frameInfos = new List<FrameInfo>();

            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(Tools.Database.BlockTableId, OpenMode.ForRead);
                foreach (ObjectId blockId in table)
                {
                    BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                    if (IsVersionType(record.Name))  //如果此块定义名符合图框块名
                    {
                        ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(true, true);  //取得此块定义所关联的所有块参照Id
                        foreach (ObjectId blockRefId in blockRefIds)
                        {
                            FrameInfo frameInfo = new FrameInfo();
                            //frameInfo.Type = (FrameVersionType)Enum.Parse(typeof(FrameVersionType), record.Name);
                            BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                            AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                            List<AttributeReference> attrRefs = new List<AttributeReference>();
                            foreach (ObjectId attrRefId in blockRefAttrs)
                            {
                                AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForRead);
                                attrRefs.Add(attrRef);
                            }
                            frameInfo.LoadFromAttrRefs(attrRefs);
                            frameInfos.Add(frameInfo);
                        }
                    }
                }
            }
            return frameInfos;
        }

        // 设置当前文件中所有的图框字段，并友情返回所有图框信息
        public static List<FrameInfo> SetFrameInfo(string attributeName, string attributeValue)
        {
            List<FrameInfo> frameInfos = new List<FrameInfo>();

            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(Tools.Database.BlockTableId, OpenMode.ForRead);
                foreach (ObjectId blockId in table)
                {
                    BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                    if (IsVersionType(record.Name))  //如果此块定义名符合图框块名
                    {
                        ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(true, true);  //取得此块定义所关联的所有块参照Id
                        foreach (ObjectId blockRefId in blockRefIds)
                        {
                            FrameInfo frameInfo = new FrameInfo();
                            //frameInfo.Type = (FrameVersionType)Enum.Parse(typeof(FrameVersionType), record.Name);
                            BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                            AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                            List<AttributeReference> attrRefs = new List<AttributeReference>();
                            foreach (ObjectId attrRefId in blockRefAttrs)
                            {
                                AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForWrite);
                                if (attrRef.Tag == attributeName)
                                {
                                    attrRef.TextString = attributeValue;
                                }
                                attrRefs.Add(attrRef);
                            }
                            frameInfo.LoadFromAttrRefs(attrRefs);
                            frameInfos.Add(frameInfo);
                        }
                    }
                }
                trans.Commit();
            }
            return frameInfos;
        }

        public static FrameInfo SetSingleFrameInfo(Transaction trans, ObjectId blockRefId, FrameInfo destFrameInfo, string strCTB,int plus)
        {
            FrameInfo frameInfo = new FrameInfo();
            //frameInfo.Type = (FrameVersionType)Enum.Parse(typeof(FrameVersionType), record.Name);
            frameInfo.Type = destFrameInfo.Type;
            BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForWrite);
            AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
            List<AttributeReference> attrRefs = new List<AttributeReference>();
            CommandSign.SetCTB(trans, blockRefId, destFrameInfo.strCTB);
            foreach (ObjectId attrRefId in blockRefAttrs)
            {
                AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForWrite);
                string dc = "DescriptionChinese" + (char)(destFrameInfo.versionList.versionList.Count - 1 + 'A');
                string de = "DescriptionEnglish" + (char)(destFrameInfo.versionList.versionList.Count - 1 + 'A');
                if (attrRef.Tag == dc)
                {
//                    MessageBox.Show(destFrameInfo.DescriptionChinese);
                    attrRef.TextString = destFrameInfo.DescriptionChinese;
                }
                else if (attrRef.Tag == de)
                {
                    attrRef.TextString = destFrameInfo.DescriptionEnglish;
                }
                switch (attrRef.Tag)
                {
                    case "ClientChinese":
                        attrRef.TextString = destFrameInfo.ClientChinese;
                        break;
                    case "ClientEnglish":
                        attrRef.TextString = destFrameInfo.ClientEnglish;
                        break;
                    case "ProjectNameChinese":
                        attrRef.TextString = destFrameInfo.ProjectNameChinese;
                        break;
                    case "ProjectNameEnglish":
                        attrRef.TextString = destFrameInfo.ProjectNameEnglish;
                        break;
                    case "SubProjectChinese":
                        attrRef.TextString = destFrameInfo.SubProjectChinese;
                        break;
                    case "SubProjectEnglish":
                        attrRef.TextString = destFrameInfo.SubProjectEnglish;
                        break;
                    case "ProjectNo":
                        attrRef.TextString = destFrameInfo.ProjectNo;
                        break;
                    case "SubProjectNo":
                        attrRef.TextString = destFrameInfo.SubProjectNo;
                        break;
                    case "SheetTitleChinese":
                        attrRef.TextString = destFrameInfo.SheetTitleChinese;
                        break;
                    case "SheetTitleEnglish":
                        attrRef.TextString = destFrameInfo.SheetTitleEnglish;
                        break;
                    case "DisciplineChinese":
                        attrRef.TextString = destFrameInfo.DisciplineChinese;
                        break;
                    case "DisciplineEnglish":
                        attrRef.TextString = destFrameInfo.DisciplineEnglish;
                        break;
                    case "StageChinese":
                        attrRef.TextString = destFrameInfo.StageChinese;
                        break;
                    case "StageEnglish":
                        attrRef.TextString = destFrameInfo.StageEnglish;
                        break;
                    case "SheetNo":
                        attrRef.TextString = destFrameInfo.SheetNo;
                        break;
                    case "Rev2":
                        string tt = "";
                        tt += (char)(destFrameInfo.versionList.versionList.Count - 1 + 'A');
                        attrRef.TextString = tt;
                        break;
                     case "ReviewedBy":
                         attrRef.TextString = "";
                         break;
                }
                attrRefs.Add(attrRef);
            } 
            SetVersionInfo(trans, blockRefId, destFrameInfo.versionList, destFrameInfo.DescriptionChinese, destFrameInfo.DescriptionEnglish,plus);
         
            frameInfo.LoadFromAttrRefs(attrRefs);

            String DwgName = CommandSplit.GetFileNameFromFrame(blockRef);
            FileInfo fi = new FileInfo(Tools.Database.Filename);
            Function.Function_PlotStyle.UploadPlotStyle(strCTB, DwgName, fi.Directory.FullName);
            return frameInfo;
        }


        [CommandMethod("setit")]
        public static void setit()
        {
            List<FrameInfo> list = SetFrameInfo("ApprovedBy", "Jerry");
            foreach (FrameInfo frame in list)
            {
                Tools.WriteMessageWithReturn(frame.ApprovedBy.Name);
            }
        }

        //         [CommandMethod("setframe")]
        //         public static void setframe()
        //         {
        //             List<FrameInfo> list = GetFrameInfo();
        //             Form.FormSettingFrameInfo form = new Form.FormSettingFrameInfo(list[0], true);
        //             if(form.ShowDialog()==DialogResult.OK)
        //             {
        //                 SetFrameInfo(form.frameInfo);
        //             }
        // 
        //         }
        public static void SetFrameById(ObjectId id, bool first, string virtualtorealfalg)//这里的virtualtorealfalg标记主要是告诉FormSettingFrameInfo，设计人员作了什么命令
        {
            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                string strCTB = "";
                List<string> listCTB = new List<string>();
                FrameInfo frameInfo = GetSingleFrameInfo(trans, id, ref strCTB);
                string path = null; 
                PlotSettingsValidator psv = PlotSettingsValidator.Current;

                //这里获取的路径信息中含有项目和子项目名称，其实按这种方式获取是不合理的，它的实际值是类似于C:\sim\XXX-XXX.ini的配置文件路径信息
                path = getProInfoPath(Application.DocumentManager.MdiActiveDocument.Database.Filename);
                if (path == "")
                {
                   // MessageBox.Show("文件位置错误！\n请将文件放置到指定文件夹！");
                    MessageBox.Show("您的操作不正确!\n请按流程操作才能获取相关的项目信息!");
                    return;
                }
                //这一个else从数据库里导出项目信息，其实这一部分可以进行封装，.......
                else
                {
                    ProjectInformationService projectInformationService=new ProjectInformationService();
                    //根据获取项目图纸的路径，来获得项目名称和子项目名称
                    Hashtable PnAndSPn = projectInformationService.getPnAndSubPn(path);
                    string projectNumber = PnAndSPn["pn"].ToString();
                    string subProjectNumber = PnAndSPn["spn"].ToString();
                    ProjectInformation projectInfo = projectInformationService.getProjectInFo(projectNumber,subProjectNumber);
                    if (projectInfo != null)
                    {
                        frameInfo.ClientChinese = projectInfo.CCSC;
                        frameInfo.ClientEnglish = projectInfo.CCE;
                        frameInfo.ProjectNameChinese = projectInfo.PNSC;
                        frameInfo.ProjectNameEnglish = projectInfo.PNE;
                        frameInfo.SubProjectChinese = projectInfo.SPNSC;
                        frameInfo.SubProjectEnglish = projectInfo.SPNE;
                        frameInfo.ProjectNo = projectInfo.PN;
                        frameInfo.SubProjectNo = projectInfo.SPN;
                    }
                    else
                    {
                        MessageBox.Show("数据库导出数据发生了错误！\n请联系管理人员！");
                        return;
                    }
                }
                //被注释掉这一部分是先前开发人员从配置文件中导出项目相关信息
              /*  if (File.Exists(path))
                {
                    MessageBox.Show(path);
                    StringBuilder strb_temp = new StringBuilder(256);
                    Extern.GetPrivateProfileString("FrameInfo", "CCSC", "", strb_temp, 512, path);
                    frameInfo.ClientChinese = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "CCE", "", strb_temp, 512, path);
                    frameInfo.ClientEnglish = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "PNSC", "", strb_temp, 512, path);
                    frameInfo.ProjectNameChinese = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "PNE", "", strb_temp, 512, path);
                    frameInfo.ProjectNameEnglish = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "SPNSC", "", strb_temp, 512, path);
                    frameInfo.SubProjectChinese = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "SPNE", "", strb_temp, 512, path);
                    frameInfo.SubProjectEnglish = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "PN", "", strb_temp, 512, path);
                    frameInfo.ProjectNo = strb_temp.ToString();
                    Extern.GetPrivateProfileString("FrameInfo", "SPN", "", strb_temp, 512, path);
                    frameInfo.SubProjectNo = strb_temp.ToString();
                }
                else
                {
                    MessageBox.Show("配置文件不存在!" + path);
                    return;
                }*/
                //sc里经过测试里边是，act.tb......一些东西，目前不知道它的作用
                System.Collections.Specialized.StringCollection sc = psv.GetPlotStyleSheetList();
                foreach (string str in sc)
                {
                    listCTB.Add(str);
                }
                Form.FormSettingFrameInfo form = new Form.FormSettingFrameInfo(frameInfo, true, listCTB, strCTB, first, virtualtorealfalg);
                form.ShowDialog();
                SetSingleFrameInfo(trans, id, form.frameInfo, frameInfo.strCTB,0);

                trans.Commit();
            }
        }
        /// <summary>
        /// 设置选中图框的属性
        /// </summary>
        [CommandMethod("setselectedframe")]
        public static void SetSelectedFrame()
        {
            Editor ed = Tools.Editor;
            //PromptSelectionOptions pso = new PromptSelectionOptions();
            //pso.MessageForAdding = "Select BlockReference:";
            //TypedValue[] tvs = new TypedValue[]{
            //    new TypedValue((int)DxfCode.Start, "BLOCKREFERENCE")
            //};
            //SelectionFilter filter = new SelectionFilter(tvs);
            ObjectId selId;
            while (true)
            {
                PromptEntityResult per = ed.GetEntity("请选择一个图框");
                if (per.Status != PromptStatus.OK)
                    return;
                selId = per.ObjectId;
                if (Tools.GetEntity(selId) is Autodesk.AutoCAD.DatabaseServices.BlockReference)
                {
                    break;//这里有些问题，选中直线的时候也break了……
                }
            }
            SetFrameById(selId, false,CONSTCOMMAND.SETSELECTEDFRAME);
        }

        [CommandMethod("testinsert")]
        public static void testinsert()
        {
            PromptPointResult result = Tools.Editor.GetPoint("请选择插入点");
            if (result.Status != PromptStatus.OK)
                return;
            Point3d pos = result.Value;
            Tools.InsertBlockReference("0", "test", pos, new Scale3d(1), 0);


        }


        /// <summary>
        /// 载入、插入图框并设置图框信息
        /// </summary>
        [CommandMethod("loadinsertset")]
        public static void loadinsertset()
        {
            //tempInsertFunc();
            LoadInsertSetEx();
        }

        private static void tempInsertFunc()
        {
            FrameInfo frameInfo = new FrameInfo();
            List<string> listCTB = new List<string>();
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            System.Collections.Specialized.StringCollection sc = psv.GetPlotStyleSheetList();
            string path = "";
            foreach (string str in sc)
            {
                if (!str.EndsWith("stb"))
                {
                    listCTB.Add(str);
                }
            }
           
            path = getProInfoPath(Application.DocumentManager.MdiActiveDocument.Database.Filename);
            if (path == "")
            {
                //MessageBox.Show("文件位置错误！\n请将文件放置到指定文件夹！");
                MessageBox.Show("您的操作不正确!\n请按流程操作才能获取相关的项目信息!");

            }
            else
            {
                ProjectInformationService projectInformationService = new ProjectInformationService();
                //根据获取项目图纸的路径，来获得项目名称和子项目名称
                Hashtable PnAndSPn = projectInformationService.getPnAndSubPn(path);
                string projectNumber = PnAndSPn["pn"].ToString();
                string subProjectNumber = PnAndSPn["spn"].ToString();
                ProjectInformation projectInfo = projectInformationService.getProjectInFo(projectNumber, subProjectNumber);
                if (projectInfo != null)
                {
                    frameInfo.ClientChinese = projectInfo.CCSC;
                    frameInfo.ClientEnglish = projectInfo.CCE;
                    frameInfo.ProjectNameChinese = projectInfo.PNSC;
                    frameInfo.ProjectNameEnglish = projectInfo.PNE;
                    frameInfo.SubProjectChinese = projectInfo.SPNSC;
                    frameInfo.SubProjectEnglish = projectInfo.SPNE;
                    frameInfo.ProjectNo = projectInfo.PN;
                    frameInfo.SubProjectNo = projectInfo.SPN;
                    frameInfo.frameType = "A0";
                    frameInfo.scale = 100;
                }
                else
                {
                    MessageBox.Show("数据库导出数据发生了错误！\n请联系管理人员！");
                    return;
                }
            }
           /* if (File.Exists(path))
            {
                MessageBox.Show(path);
                StringBuilder strb_temp = new StringBuilder(256);
                Extern.GetPrivateProfileString("FrameInfo", "CCSC", "", strb_temp, 512, path);
                frameInfo.ClientChinese = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "CCE", "", strb_temp, 512, path);
                frameInfo.ClientEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PNSC", "", strb_temp, 512, path);
                frameInfo.ProjectNameChinese = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PNE", "", strb_temp, 512, path);
                frameInfo.ProjectNameEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPNSC", "", strb_temp, 512, path);
                frameInfo.SubProjectChinese = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPNE", "", strb_temp, 512, path);
                frameInfo.SubProjectEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PN", "", strb_temp, 512, path);
                frameInfo.ProjectNo = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPN", "", strb_temp, 512, path);
                frameInfo.SubProjectNo = strb_temp.ToString();
                frameInfo.frameType = "A0";
                frameInfo.scale = 100;
            }
            else
            {
                MessageBox.Show("配置文件不存在!" + path);
                return;
            }*/

            Form.FormSettingFrameInfo form = new Form.FormSettingFrameInfo(frameInfo, true, listCTB, frameInfo.strCTB, true,"");
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadActualFrame("TJAD_TK_" + form.frameInfo.frameType + "_A");
                Point3d pos;
                PromptPointResult result = Tools.Editor.GetPoint("请选择插入点");
                if (result.Status != PromptStatus.OK)
                    return;
                pos = result.Value;
                //---------------------------------------------------------------------
                Database db = Tools.Database;
                db.Clayer = TK_Layer();
                ObjectId blockRefId;
                string frameName = "TJAD_TK_" + form.frameInfo.frameType + "_A";
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    ObjectId currentLayerId = db.Clayer;

                    BlockTable table = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                    BlockTableRecord frameRecord = null;
                    frameRecord = trans.GetObject(table[frameName], OpenMode.ForWrite) as BlockTableRecord;
                    BlockReference bref = new BlockReference(pos, frameRecord.ObjectId);

                    BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);

                    btr.AppendEntity(bref);
                    bref.ScaleFactors = new Scale3d(form.frameInfo.scale);

                    foreach (ObjectId id in frameRecord)
                    {
                        Entity ent = trans.GetObject(id, OpenMode.ForRead, false) as Entity;
                        if (ent is AttributeDefinition)
                        {
                            AttributeReference attrToAdd = new AttributeReference();
                            AttributeDefinition attrDef = ent as AttributeDefinition;

                            attrToAdd.SetAttributeFromBlock(attrDef, bref.BlockTransform);
                            bref.AttributeCollection.AppendAttribute(attrToAdd);
                            trans.AddNewlyCreatedDBObject(attrToAdd, true);
                        }

                    }

                    trans.AddNewlyCreatedDBObject(bref, true);
                    blockRefId = bref.ObjectId;
                    SetSingleFrameInfo(trans, bref.ObjectId, form.frameInfo, frameInfo.strCTB,1);
                    AttributeCollection ac = bref.AttributeCollection;
                    foreach (ObjectId arId in ac)
                    {
                        AttributeReference ar = trans.GetObject(arId, OpenMode.ForWrite) as AttributeReference;
                        if (ar.Tag == "DateA")
                        {
                            ar.TextString = System.DateTime.Now.ToString("yy.MM.dd");
                        }
                        else if ((ar.Tag == "RevA") || (ar.Tag == "Rev2"))
                        {
                            ar.TextString = "A";
                        }
                        else if (ar.Tag == "DescriptionChineseA")
                        {
                            ar.TextString = form.frameInfo.DescriptionChinese;
                        }
                        else if (ar.Tag == "DescriptionEnglishA")
                        {
                            ar.TextString = form.frameInfo.DescriptionEnglish;
                        }
                    }
                    trans.Commit();
                }
                   }
        }

        /// <summary>
        /// 调试功能
        /// </summary>
        [CommandMethod("printit")]
        public static void printit()
        {
            List<FrameInfo> list = GetFrameInfo();
            foreach (FrameInfo frame in list)
            {
                Tools.WriteMessageWithReturn(frame.ApprovedBy.Name);
            }
        }

        [CommandMethod("versionupdate")]
        public static void versionupdate()
        {
            VersionUpdateEx();
        }

        public static void SetVersionInfo(Transaction trans, ObjectId FrameId, VersionList vl, string chinese, string english,int plus)
        {
            BlockReference frame = trans.GetObject(FrameId, OpenMode.ForWrite) as BlockReference;
            AttributeCollection ac = frame.AttributeCollection;
            foreach (ObjectId id in ac)
            {
                AttributeReference ar = trans.GetObject(id, OpenMode.ForWrite) as AttributeReference;
                if (ar.Tag == "Date" + transferVersion(vl.versionList.Count + plus))
                {
                    ar.TextString = System.DateTime.Now.ToString("yy.MM.dd");
                }
                else if (ar.Tag == "DescriptionChinese" + transferVersion(vl.versionList.Count + plus))
                {
                    ar.TextString = chinese;
                }
                else if (ar.Tag == "DescriptionEnglish" + transferVersion(vl.versionList.Count + plus))
                {
                    ar.TextString = english;
                }
                else if ((ar.Tag == "Rev" + transferVersion(vl.versionList.Count + plus)) || (ar.Tag == "Rev2"))
                {
                    string temp = "";
                    temp += transferVersion(vl.versionList.Count + plus);
                    ar.TextString = temp;
                }
                else if (ar.Tag.StartsWith("Date"))
                {
                    int n_version = VersionStrToInt(ar.Tag.Substring("Date".Length, ar.Tag.Length - "Date".Length)) - 1;
                    VersionInfo newvi = new VersionInfo();
                    vl.versionList.TryGetValue(n_version, out newvi);
                    ar.TextString = newvi.date;
                }
                else if (ar.Tag.StartsWith("DescriptionChinese"))
                {
                    int n_version = VersionStrToInt(ar.Tag.Substring("DescriptionChinese".Length, ar.Tag.Length - "DescriptionChinese".Length)) - 1;
                    VersionInfo newvi = new VersionInfo();
                    vl.versionList.TryGetValue(n_version, out newvi);
                    ar.TextString = newvi.descriptionChinese;
                }
                else if (ar.Tag.StartsWith("DescriptionEnglish"))
                {
                    int n_version = VersionStrToInt(ar.Tag.Substring("DescriptionEnglish".Length, ar.Tag.Length - "DescriptionEnglish".Length)) - 1;
                    VersionInfo newvi = new VersionInfo();
                    vl.versionList.TryGetValue(n_version, out newvi);
                    ar.TextString = newvi.descriptionEnglish;
                }
                else if ((ar.Tag.StartsWith("Rev")) && (ar.Tag != "Rev2")&&(!ar.Tag.StartsWith("Review")))
                {
                    int n_version = VersionStrToInt(ar.Tag.Substring("Rev".Length, ar.Tag.Length - "Rev".Length));
                    ar.TextString = transferVersion(n_version);
                }
                else if (ar.Tag == "ReviewedBy")
                {
                    ar.TextString = "";
                }
                else if (ar.Tag == "ReviewedBySignPos")
                {
                    ar.TextString = "";
                }
            }
        }

        [CommandMethod("virtualinsert")]
        public static void virtualinsert()
        {
            string frameNameTemp = SelectFrame();
            if (frameNameTemp == "")
                return;
            string frameName = frameNameTemp.Substring(0, 5) + "VF" + frameNameTemp.Substring(7, frameNameTemp.Length - 7);
            LoadActualFrame(frameName);
            Database db = Tools.Database;
            db.Clayer = TK_Layer();
            Point3d pos;

            PromptPointResult result = Tools.Editor.GetPoint("请选择插入点");
            if (result.Status != PromptStatus.OK)
                return;
            pos = result.Value;

            PromptIntegerResult result2 = Tools.Editor.GetInteger("请输入比例");
            if (result.Status != PromptStatus.OK)
                return;
            int Scale = result2.Value;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable table = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord modelSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                BlockTableRecord frameRecord = trans.GetObject(table[frameName], OpenMode.ForRead) as BlockTableRecord;
                BlockReference newFrameReference = new BlockReference(pos, frameRecord.ObjectId);
                newFrameReference.ScaleFactors = new Scale3d(Scale);
                modelSpace.AppendEntity(newFrameReference);
                trans.AddNewlyCreatedDBObject(newFrameReference, true);
                trans.Commit();
            }
        }

        [CommandMethod("virtualtoreal")]
        public static void virtualtoreal()
        {
            VirtualToRealEx();
        }

        public static string getProInfoPath(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            DirectoryInfo di = fi.Directory;

            if (di == null)
            {
                return String.Empty;
            }
            while (((di.Name[0] < '0') || (di.Name[0] > '9')) || ((di.Parent.Name[0] < '0') || (di.Parent.Name[0] > '9')))
            {
                di = di.Parent;
                if (di.FullName == di.Root.FullName) return "";
            }
            return Config.ProjectInfoPath + di.Parent.Name + '-' + di.Name + ".ini";
            
        }

        public static bool IsVersionType(string frameVersionName)
        {
            if (frameVersionName == "")
            {
                return false;
            }
            bool isVersionType = false;
            string frameName = "";
            int iLength = 0;
            while (frameVersionName[frameVersionName.Length - iLength - 1] != '_')
            {
                ++iLength;
                if (frameVersionName.Length == iLength)
                {
                    return false;
                }
            }
            frameName = frameVersionName.Substring(0, frameVersionName.Length - iLength - 1);
            if (Enum.GetNames(typeof(FrameType)).Contains(frameName))
            {
                isVersionType = true;
            }
            return isVersionType;
        }

        public static void LoadInsertSetEx()
        {
            FrameInfo frameInfo = lastFrameInfo;
            List<string> listCTB = new List<string>();
            PlotSettingsValidator psv = PlotSettingsValidator.Current;
            System.Collections.Specialized.StringCollection sc = psv.GetPlotStyleSheetList();
            string path = "";
            foreach (string str in sc)
            {
                if (!str.EndsWith("stb"))
                {
                    listCTB.Add(str);
                }
            }
            //我将要修改这里
            path = getProInfoPath(Application.DocumentManager.MdiActiveDocument.Database.Filename);
            if (path == "")
            {
                //MessageBox.Show("文件位置错误！\n请将文件放置到指定文件夹！");
                MessageBox.Show("您的操作不正确!\n请按流程操作才能获取相关的项目信息!");
                return;
            }
            else
            {
                ProjectInformationService projectInformationService = new ProjectInformationService();
                //根据获取项目图纸的路径，来获得项目名称和子项目名称
                Hashtable PnAndSPn = projectInformationService.getPnAndSubPn(path);
                string projectNumber = PnAndSPn["pn"].ToString();
                string subProjectNumber = PnAndSPn["spn"].ToString();
                ProjectInformation projectInfo = projectInformationService.getProjectInFo(projectNumber, subProjectNumber);
                if (projectInfo != null)
                {
                    frameInfo.ClientChinese = projectInfo.CCSC;
                    frameInfo.ClientEnglish = projectInfo.CCE;
                    frameInfo.ProjectNameChinese = projectInfo.PNSC;
                    frameInfo.ProjectNameEnglish = projectInfo.PNE;
                    frameInfo.SubProjectChinese = projectInfo.SPNSC;
                    frameInfo.SubProjectEnglish = projectInfo.SPNE;
                    frameInfo.ProjectNo = projectInfo.PN;
                    frameInfo.SubProjectNo = projectInfo.SPN;

                    if (frameInfo.frameType == null)
                    {
                        frameInfo.frameType = "A0";
                        frameInfo.scale = 100;
                    }
                }
                else
                {
                    MessageBox.Show("数据库导出数据发生了错误！\n请联系管理人员！");
                    return;
                }
            }
            /*if (File.Exists(path))
            {
           //  这里是从配置文件读取项目信息的代码
                MessageBox.Show(path);
                StringBuilder strb_temp = new StringBuilder(256);
                Extern.GetPrivateProfileString("FrameInfo", "CCSC", "", strb_temp, 512, path);
                frameInfo.ClientChinese = strb_temp.ToString();
                 Extern.GetPrivateProfileString("FrameInfo", "CCE", "", strb_temp, 512, path);
                frameInfo.ClientEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PNSC", "", strb_temp, 512, path);
                //frameInfo.ProjectNameChinese = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PNE", "", strb_temp, 512, path);
                frameInfo.ProjectNameEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPNSC", "", strb_temp, 512, path);
                frameInfo.SubProjectChinese = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPNE", "", strb_temp, 512, path);
                frameInfo.SubProjectEnglish = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "PN", "", strb_temp, 512, path);
                frameInfo.ProjectNo = strb_temp.ToString();
                Extern.GetPrivateProfileString("FrameInfo", "SPN", "", strb_temp, 512, path);
                frameInfo.SubProjectNo = strb_temp.ToString();
               
                if (frameInfo.frameType == null)
                {
                    frameInfo.frameType = "A0";
                    frameInfo.scale = 100;
                }
            }
            else
            {
                MessageBox.Show("配置文件不存在!" + path);
                return;
            }*/
            Form.FormSettingFrameInfo form = new Form.FormSettingFrameInfo(frameInfo, true, listCTB, frameInfo.strCTB, true,CONSTCOMMAND.LOADINSERTSET);
            form.ShowDialog();
            if (!form.set)
            {
                return;
            }
            Point3d pos;
            PromptPointResult result = Tools.Editor.GetPoint("请选择插入点");
            if (result.Status != PromptStatus.OK)
                return;
            pos = result.Value;
            InsertFrameEx(form.frameInfo, pos, 1, "TJAD_TK_" + form.frameInfo.frameType, Tools.Database, new Scale3d(form.frameInfo.scale));
        }

        public static void VersionUpdateEx()
        {
            Editor ed = Tools.Editor;
            ObjectId selId;
            while (true)
            {
                PromptEntityResult per = ed.GetEntity("请选择一个图框");
                if (per.Status != PromptStatus.OK)
                    return;
                selId = per.ObjectId;
                if (Tools.GetEntity(selId) is Autodesk.AutoCAD.DatabaseServices.BlockReference)
                {
                    if (IsVersionType(((BlockReference)Tools.GetEntity(selId)).Name))
                    {
                        break;
                    }
                }
            }
            Form.VersionForm vf = new Form.VersionForm();
            vf.ShowDialog();
            if (vf.DescriptionChinese == "")
            {
                MessageBox.Show("信息不完整!");
                return;
            }
            FrameInfo frameInfo;
            Point3d position;
            int version;
            string frameName;
            string temp = "";
            Scale3d scale;
            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockReference oldFrame = trans.GetObject(selId, OpenMode.ForRead) as BlockReference;
                frameInfo = GetSingleFrameInfo(trans, selId, ref temp);
                position = oldFrame.Position;
                scale = oldFrame.ScaleFactors;
                version = getVersionInt(oldFrame.Name);
                frameName = getFrameName(oldFrame.Name);
            }
            frameInfo.DescriptionChinese = vf.DescriptionChinese;
            frameInfo.DescriptionEnglish = vf.DescriptionEnglish;
            InsertFrameEx(frameInfo, position, version + 1, frameName, Tools.Database, scale);
            using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
            {
                BlockReference oldFrame = trans.GetObject(selId, OpenMode.ForWrite) as BlockReference;
                oldFrame.Erase();
                trans.Commit();
            }
        }

        public static void VirtualToRealEx()
        {
            Editor ed = Tools.Editor;
            ObjectId selId;
            Point3d pos = new Point3d();
            Scale3d scale = new Scale3d();
            string vfName = "";
            while (true)
            {
                PromptEntityResult per = ed.GetEntity("请选择一个图框");
                if (per.Status != PromptStatus.OK)
                    return;
                selId = per.ObjectId;
                if (Tools.GetEntity(selId) is Autodesk.AutoCAD.DatabaseServices.BlockReference)
                {
                    if (Enum.GetNames(typeof(VirtualFrameType)).Contains(((BlockReference)Tools.GetEntity(selId)).Name))
                    {
                        using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
                        {
                            BlockReference frame = trans.GetObject(selId, OpenMode.ForRead) as BlockReference;
                            pos = frame.Position;
                            scale = frame.ScaleFactors;
                            vfName = frame.Name;
                        }
                        FrameInfo frameInfo = lastFrameInfo;
                        List<string> listCTB = new List<string>();
                        PlotSettingsValidator psv = PlotSettingsValidator.Current;
                        System.Collections.Specialized.StringCollection sc = psv.GetPlotStyleSheetList();
                        string path = "";
                        foreach (string str in sc)
                        {
                            if (!str.EndsWith("stb"))
                            {
                                listCTB.Add(str);
                            }
                        }

                        path = getProInfoPath(Application.DocumentManager.MdiActiveDocument.Database.Filename);
                        if (path == "")
                        {
                            // MessageBox.Show("文件位置错误！\n请将文件放置到指定文件夹！");
                            MessageBox.Show("您的操作不正确!\n请按流程操作才能获取相关的项目信息!");
                            return;
                        }
                        else
                        {
                            ProjectInformationService projectInformationService = new ProjectInformationService();
                            //根据获取项目图纸的路径，来获得项目名称和子项目名称
                            Hashtable PnAndSPn = projectInformationService.getPnAndSubPn(path);
                            string projectNumber = PnAndSPn["pn"].ToString();
                            string subProjectNumber = PnAndSPn["spn"].ToString();
                            ProjectInformation projectInfo = projectInformationService.getProjectInFo(projectNumber, subProjectNumber);
                            if (projectInfo != null)
                            {
                                frameInfo.ClientChinese = projectInfo.CCSC;
                                frameInfo.ClientEnglish = projectInfo.CCE;
                                frameInfo.ProjectNameChinese = projectInfo.PNSC;
                                frameInfo.ProjectNameEnglish = projectInfo.PNE;
                                frameInfo.SubProjectChinese = projectInfo.SPNSC;
                                frameInfo.SubProjectEnglish = projectInfo.SPNE;
                                frameInfo.ProjectNo = projectInfo.PN;
                                frameInfo.SubProjectNo = projectInfo.SPN;

                                if (frameInfo.frameType == null)
                                {
                                    frameInfo.frameType = "A0";
                                    frameInfo.scale = 100;
                                }
                            }
                            else
                            {
                                MessageBox.Show("数据库导出数据发生了错误！\n请联系管理人员！");
                                return;
                            }
                        }
                       /* if (File.Exists(path))
                        {
                            StringBuilder strb_temp = new StringBuilder(256);
                            Extern.GetPrivateProfileString("FrameInfo", "CCSC", "", strb_temp, 512, path);
                            frameInfo.ClientChinese = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "CCE", "", strb_temp, 512, path);
                            frameInfo.ClientEnglish = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "PNSC", "", strb_temp, 512, path);
                            frameInfo.ProjectNameChinese = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "PNE", "", strb_temp, 512, path);
                            frameInfo.ProjectNameEnglish = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "SPNSC", "", strb_temp, 512, path);
                            frameInfo.SubProjectChinese = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "SPNE", "", strb_temp, 512, path);
                            frameInfo.SubProjectEnglish = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "PN", "", strb_temp, 512, path);
                            frameInfo.ProjectNo = strb_temp.ToString();
                            Extern.GetPrivateProfileString("FrameInfo", "SPN", "", strb_temp, 512, path);
                            frameInfo.SubProjectNo = strb_temp.ToString();
                            if (frameInfo.frameType == null)
                            {
                                frameInfo.frameType = "A0";
                                frameInfo.scale = 100;
                            }
                        }
                        else
                        {
                            MessageBox.Show("配置文件不存在!" + path);
                            return;
                        }*/
                        Form.FormSettingFrameInfo form = new Form.FormSettingFrameInfo(frameInfo, true, listCTB, frameInfo.strCTB, false,CONSTCOMMAND.VIRTUALTOREAL);
                        form.ShowDialog();
                        if (form.set)
                        {
                            InsertFrameEx(form.frameInfo, pos, 1, "TJAD_TK_" + getFrameType(vfName), Tools.Database, scale);
                        }
                        using (Transaction trans = Tools.Database.TransactionManager.StartTransaction())
                        {
                            Entity entity = trans.GetObject(selId, OpenMode.ForWrite) as Entity;
                            entity.Erase();
                            trans.Commit();
                        }
                        break;
                    }
                }
            }
        }

        public static void InsertFrameEx(FrameInfo frameInfo, Point3d position, int version, string frameName, Database dbToInsert, Scale3d scale)
        {
            dbToInsert.Clayer = TK_Layer();
            using (Transaction trans = dbToInsert.TransactionManager.StartTransaction())
            {
                BlockTable table = trans.GetObject(dbToInsert.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord Space = trans.GetObject(dbToInsert.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                BlockTableRecord frameRecord = getFrameRecord(trans, version, frameName, dbToInsert);
                BlockReference frameReference = new BlockReference(position, frameRecord.ObjectId);
                frameReference.ScaleFactors = scale;
                Space.AppendEntity(frameReference);
                foreach (ObjectId id in frameRecord)
                {
                    Entity ent = trans.GetObject(id, OpenMode.ForRead, false) as Entity;
                    if (ent is AttributeDefinition)
                    {
                        AttributeReference attrToAdd = new AttributeReference();
                        AttributeDefinition attrDef = ent as AttributeDefinition;
                        attrToAdd.SetAttributeFromBlock(attrDef, frameReference.BlockTransform);
                        frameReference.AttributeCollection.AppendAttribute(attrToAdd);
                        trans.AddNewlyCreatedDBObject(attrToAdd, true);
                    }
                }
                trans.AddNewlyCreatedDBObject(frameReference, true);
                AttributeCollection ac = frameReference.AttributeCollection;
                foreach (ObjectId id2 in ac)
                {
                    AttributeReference ar = trans.GetObject(id2, OpenMode.ForWrite) as AttributeReference;
                    if (ar.Tag.EndsWith("Date"))
                    {
                        ar.TextString = "00.00.00";
                    }
                    else
                    {
                        ar.TextString = String.Empty;
                    }
                }
                SetSingleFrameInfo(trans, frameReference.ObjectId, frameInfo, frameInfo.strCTB,1);
                trans.Commit();
            }
        }

        public static BlockTableRecord getFrameRecord(Transaction trans, int version, string frameName, Database dbToInsert)
        {
            BlockTableRecord frameTempRecord = null;
            string frameVersionName = frameName + '_' + (char)('A' + version - 1);
            BlockTable table = trans.GetObject(dbToInsert.BlockTableId, OpenMode.ForWrite) as BlockTable;
            foreach (ObjectId id in table)
            {
                BlockTableRecord record = trans.GetObject(id, OpenMode.ForWrite) as BlockTableRecord;
                if (record.Name == frameVersionName)
                {
                    frameTempRecord = record;
                    break;
                }
            }
            if (frameTempRecord == null)
            {
                ImportBlockToDB(frameName, dbToInsert);
                BlockTable table2 = trans.GetObject(dbToInsert.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId id in table2)
                {
                    BlockTableRecord record = trans.GetObject(id, OpenMode.ForWrite) as BlockTableRecord;
                    if (record.Name == frameName)
                    {
                        frameTempRecord = record;
                        if (record.Name.EndsWith("A2"))
                        {
                            AppendNewVerInfo2(trans, version, frameTempRecord, dbToInsert);
                        }
                        else
                        {
                            AppendNewVerInfo(trans, version, frameTempRecord, frameName, dbToInsert);
                        }
                        frameTempRecord.Name = frameVersionName;
                        break;
                    }
                }
            }
            return frameTempRecord;
        }

        public static void AppendNewVerInfo(Transaction trans, int Newversion, BlockTableRecord frameRecord, string frameName, Database db)
        {
            for (int version = 1; version <= Newversion; ++ version)
            {
                int Offset = getOffsetFromIni(frameName);
                Point3d ptDate = getPoint3dFromIni("Base", "Date", Offset, version);
                Point3d ptRev = getPoint3dFromIni("Base", "Rev", Offset, version);
                Point3d ptDc = getPoint3dFromIni("Base", "Dc", Offset, version);
                Point3d ptDe = getPoint3dFromIni("Base", "De", Offset, version);
                Point3d ptLineFrom = getPoint3dFromIni("Base", "LineFrom", Offset, version);
                Point3d ptLineTo = getPoint3dFromIni("Base", "LineTo", Offset, version);
                Point3d ptTemp = new Point3d(0, 0, 0);

                Line upLine = new Line(ptLineFrom, ptLineTo);
                frameRecord.AppendEntity(upLine);
                trans.AddNewlyCreatedDBObject(upLine, true);

                ObjectId id = new ObjectId();
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                foreach (ObjectId idTemp in tst)
                {
                    TextStyleTableRecord tstr = trans.GetObject(idTemp, OpenMode.ForRead) as TextStyleTableRecord;
                    if (tstr.Name == "TKZ1_tjhts.shx")
                    {
                        id = idTemp;
                        break;
                    }
                }
                string follow = transferVersion(version);
                AttributeDefinition Date = new AttributeDefinition(ptTemp, "", "Date" + follow, "版本日期", id);
                Date.Height = 3.6;
                Date.HorizontalMode = TextHorizontalMode.TextCenter;
                Date.VerticalMode = TextVerticalMode.TextVerticalMid;
                Date.AlignmentPoint = ptDate;
                Date.IsMTextAttributeDefinition = true;
                Date.WidthFactor = 0.525;
                Date.LockPositionInBlock = true;
                frameRecord.AppendEntity(Date);
                trans.AddNewlyCreatedDBObject(Date, true);
                AttributeDefinition Rev = new AttributeDefinition(ptTemp, "", "Rev" + follow, "版本编号", id);
                Rev.Height = 3.6;
                Rev.HorizontalMode = TextHorizontalMode.TextCenter;
                Rev.VerticalMode = TextVerticalMode.TextVerticalMid;
                Rev.AlignmentPoint = ptRev;
                Rev.IsMTextAttributeDefinition = true;
                Rev.LockPositionInBlock = true;
                frameRecord.AppendEntity(Rev);
                trans.AddNewlyCreatedDBObject(Rev, true);
                AttributeDefinition Dc = new AttributeDefinition(ptTemp, "", "DescriptionChinese" + follow, "版本说明中文", id);
                Dc.Height = 3.6;
                Dc.HorizontalMode = TextHorizontalMode.TextCenter;
                Dc.VerticalMode = TextVerticalMode.TextVerticalMid;
                Dc.AlignmentPoint = ptDc;
                Dc.IsMTextAttributeDefinition = true;
                Dc.LockPositionInBlock = true;
                frameRecord.AppendEntity(Dc);
                trans.AddNewlyCreatedDBObject(Dc, true);
                AttributeDefinition De = new AttributeDefinition(ptTemp, "", "DescriptionEnglish" + follow, "版本说明英文", id);
                De.Height = 2.2;
                De.HorizontalMode = TextHorizontalMode.TextCenter;
                De.VerticalMode = TextVerticalMode.TextVerticalMid;
                De.AlignmentPoint = ptDe;
                De.IsMTextAttributeDefinition = true;
                De.LockPositionInBlock = true;
                frameRecord.AppendEntity(De);
                trans.AddNewlyCreatedDBObject(De, true);
            }
        }

        public static void A2MakeLine(Transaction trans, int version, BlockTableRecord frameRecord)
        {
            string strTemp = null;
            double x = 0, y = 0, z = 0;
            Point3d pointFrom = new Point3d();
            Point3d pointTo = pointFrom;
            StringBuilder strb_HDtemp = new StringBuilder(64);

            Extern.GetPrivateProfileString("A2", "PointAX", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            x = Convert.ToDouble(strTemp);
            Extern.GetPrivateProfileString("A2", "Y", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            y = Convert.ToDouble(strTemp) - (version - 1) * 10;
            z = Convert.ToDouble(strTemp) - version * 10;
            pointFrom = new Point3d(x, y, 0);
            pointTo = new Point3d(x, z, 0);
            Line upLine1 = new Line(pointFrom, pointTo);
            frameRecord.AppendEntity(upLine1);
            trans.AddNewlyCreatedDBObject(upLine1, true);

            Extern.GetPrivateProfileString("A2", "PointBX", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            x = Convert.ToDouble(strTemp);
            Extern.GetPrivateProfileString("A2", "Y", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            y = Convert.ToDouble(strTemp) - (version - 1) * 10;
            z = Convert.ToDouble(strTemp) - version * 10;
            pointFrom = new Point3d(x, y, 0);
            pointTo = new Point3d(x, z, 0);
            Line upLine2 = new Line(pointFrom, pointTo);
            frameRecord.AppendEntity(upLine2);
            trans.AddNewlyCreatedDBObject(upLine2, true);

            Extern.GetPrivateProfileString("A2", "PointCX", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            x = Convert.ToDouble(strTemp);
            Extern.GetPrivateProfileString("A2", "Y", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            y = Convert.ToDouble(strTemp) - (version - 1) * 10;
            z = Convert.ToDouble(strTemp) - version * 10;
            pointFrom = new Point3d(x, y, 0);
            pointTo = new Point3d(x, z, 0);
            Line upLine3 = new Line(pointFrom, pointTo);
            frameRecord.AppendEntity(upLine3);
            trans.AddNewlyCreatedDBObject(upLine3, true);

            Extern.GetPrivateProfileString("A2", "PointAX", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            x = Convert.ToDouble(strTemp);
            Extern.GetPrivateProfileString("A2", "Y", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            y = Convert.ToDouble(strTemp) - version * 10;
            Extern.GetPrivateProfileString("A2", "PointDX", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            z = Convert.ToDouble(strTemp);
            pointFrom = new Point3d(x, y, 0);
            pointTo = new Point3d(z, y, 0);
            Line upLine4 = new Line(pointFrom, pointTo);
            frameRecord.AppendEntity(upLine4);
            trans.AddNewlyCreatedDBObject(upLine4, true);
        }

        public static void AppendNewVerInfo2(Transaction trans, int Newversion, BlockTableRecord frameRecord, Database db)
        {
            for (int version = 1; version <= Newversion; ++ version)
            {
                int Offset = 0;
                int transferedVersion = 0 - version;
                Point3d ptDate = getPoint3dFromIni("A2", "Date", Offset, transferedVersion);
                Point3d ptRev = getPoint3dFromIni("A2", "Rev", Offset, transferedVersion);
                Point3d ptDc = getPoint3dFromIni("A2", "Dc", Offset, transferedVersion);
                Point3d ptDe = getPoint3dFromIni("A2", "De", Offset, transferedVersion);
                Point3d ptTemp = new Point3d(0, 0, 0);

                A2MakeLine(trans, version, frameRecord);

                ObjectId id = new ObjectId();
                TextStyleTable tst = trans.GetObject(db.TextStyleTableId, OpenMode.ForRead) as TextStyleTable;
                foreach (ObjectId idTemp in tst)
                {
                    TextStyleTableRecord tstr = trans.GetObject(idTemp, OpenMode.ForRead) as TextStyleTableRecord;
                    if (tstr.Name == "TKZ1_tjhts.shx")
                    {
                        id = idTemp;
                        break;
                    }
                }
                string follow = transferVersion(version);
                AttributeDefinition Date = new AttributeDefinition(ptTemp, "", "Date" + follow, "版本日期", id);
                Date.Height = 3.6;
                Date.HorizontalMode = TextHorizontalMode.TextCenter;
                Date.VerticalMode = TextVerticalMode.TextVerticalMid;
                Date.AlignmentPoint = ptDate;
                Date.WidthFactor = 0.525;
                Date.IsMTextAttributeDefinition = true;
                Date.LockPositionInBlock = true;
                frameRecord.AppendEntity(Date);
                trans.AddNewlyCreatedDBObject(Date, true);
                AttributeDefinition Rev = new AttributeDefinition(ptTemp, "", "Rev" + follow, "版本编号", id);
                Rev.Height = 3.6;
                Rev.HorizontalMode = TextHorizontalMode.TextCenter;
                Rev.VerticalMode = TextVerticalMode.TextVerticalMid;
                Rev.AlignmentPoint = ptRev;
                Rev.IsMTextAttributeDefinition = true;
                Rev.LockPositionInBlock = true;
                frameRecord.AppendEntity(Rev);
                trans.AddNewlyCreatedDBObject(Rev, true);
                AttributeDefinition Dc = new AttributeDefinition(ptTemp, "", "DescriptionChinese" + follow, "版本说明中文", id);
                Dc.Height = 3.6;
                Dc.HorizontalMode = TextHorizontalMode.TextCenter;
                Dc.VerticalMode = TextVerticalMode.TextVerticalMid;
                Dc.AlignmentPoint = ptDc;
                Dc.IsMTextAttributeDefinition = true;
                Dc.LockPositionInBlock = true;
                frameRecord.AppendEntity(Dc);
                trans.AddNewlyCreatedDBObject(Dc, true);
                AttributeDefinition De = new AttributeDefinition(ptTemp, "", "DescriptionEnglish" + follow, "版本说明英文", id);
                De.Height = 2.2;
                De.HorizontalMode = TextHorizontalMode.TextCenter;
                De.VerticalMode = TextVerticalMode.TextVerticalMid;
                De.AlignmentPoint = ptDe;
                De.IsMTextAttributeDefinition = true;
                De.LockPositionInBlock = true;
                frameRecord.AppendEntity(De);
                trans.AddNewlyCreatedDBObject(De, true);
            }
        }

        public static int getVersionInt(string frameVersionName)
        {
            int version = 0;
            int iLength = 0;
            while (frameVersionName[frameVersionName.Length - iLength - 1] != '_')
            {
                ++ iLength;
            }
            version = VersionStrToInt(frameVersionName.Substring(frameVersionName.Length - iLength, iLength));
            return version;
        }

        public static int VersionStrToInt(string VersionStr)
        {
            int i = 0;
            int level = 1;
            for (int iCount = VersionStr.Length - 1; iCount >= 0; -- iCount )
            {
                i += ((int)(VersionStr[iCount] - 'A') + 1) * level;
                level *= 26;
            }
            return i;
        }

        public static string getFrameName(string frameVersionName)
        {
            string frameName = "";
            int iLength = 0;
            while (frameVersionName[frameVersionName.Length - iLength - 1] != '_')
            {
                ++iLength;
            }
            frameName = frameVersionName.Substring(0, frameVersionName.Length - iLength - 1);
            return frameName;
        }

        public static string transferVersion(int version)
        {
            string follow = "";
            if (version <= 26)
            {
                follow += (char)('A' + version - 1);
            }
            else
            {
                follow += (char)('A' + version / 26 - 1);
                follow += (char)('A' + version % 26 - 1);
            }
            return follow;
        }

        public static Point3d getPoint3dFromIni(string tag, string item, int Offset, int version)
        {
            string strTemp = null;
            double x = 0, y = 0;
            StringBuilder strb_HDtemp = new StringBuilder(64);
            Extern.GetPrivateProfileString(tag, item + 'X', "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            x = Convert.ToDouble(strTemp) + Offset;
            Extern.GetPrivateProfileString(tag, item + 'Y', "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            y = Convert.ToDouble(strTemp) + version * 10;
            Point3d returnValue = new Point3d(x, y, 0);
            return returnValue;
        }

        public static int getOffsetFromIni(string frameName)
        {
            int i = 0;
            int iCount = frameName.Length - 1;
            for (; iCount >= 0; --iCount)
            {
                if (frameName[iCount] == '_')
                {
                    break;
                }
            }
            string strTemp = frameName.Substring(iCount + 1);
            StringBuilder strb_HDtemp = new StringBuilder(64);
            Extern.GetPrivateProfileString(strTemp, "Offset", "", strb_HDtemp, 64, Config.StdFrameInfoFile);
            strTemp = strb_HDtemp.ToString();
            i = Convert.ToInt32(strTemp);
            return i;
        }

        public static void ImportBlockToDB(string frameName, Database db)
        {
            DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            string framePath = Config.FramePath + frameName + ".dwg";
            Tools.WriteMessageWithReturn(frameName);
            //从图框文件中读出图框块
            ObjectIdCollection blockIds = new ObjectIdCollection();
            Database srcDB = new Database(false, true);
            try
            {
                srcDB.ReadDwgFile(framePath, System.IO.FileShare.Read, true, "");
            }
            catch (System.Exception ex)
            {
                Tools.WriteMessageWithReturn(ex.ToString());
            }
            using (Transaction trans = srcDB.TransactionManager.StartTransaction())
            {
                BlockTable table = (BlockTable)trans.GetObject(srcDB.BlockTableId, OpenMode.ForRead, false);
                foreach (ObjectId blockId in table)
                {
                    BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                    if (!record.IsAnonymous && !record.IsLayout && record.Name == frameName)
                    {
                        blockIds.Add(blockId);
                    }
                }
            }
            //将图框块复制到当前数据库中
            IdMapping mapping = new IdMapping();
            srcDB.WblockCloneObjects(blockIds, db.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);

            Tools.WriteMessageWithReturn(string.Format("从{0}复制了{1}个块到当前数据库中", framePath, blockIds.Count));
            srcDB.Dispose();
        }

        public static string ConvertToUnicode(string source)
        {
            string returnValue = "";
            string temp = "";
            if (!string.IsNullOrEmpty(source))
            {
                for (int i = 0; i < source.Length; i++)
                {
                    //将中文字符转为10进制整数，然后转为16进制unicode字符
                    temp = ((ushort)source[i]).ToString("x");
                    if (temp.Length <= 2)
                        temp = "00" + temp;
                    returnValue += "\\u" + temp;
                }
            }
            return returnValue;
        }

        public static string getFrameType(string virtualFrameName)
        {
            string returnValue = "";
            int iLength = virtualFrameName.Length - 1;
            while (virtualFrameName[iLength] != '_')
            {
                -- iLength;
            }
            returnValue = virtualFrameName.Substring(iLength + 1, virtualFrameName.Length - iLength - 1);
            return returnValue;
        }
    }
}
